<?php

namespace app\admin\controller\handler;

use app\common\controller\Backend;
use think\Db;

/**
 * 打手管理
 *
 * @icon fa fa-circle-o
 */
class Handler extends Backend
{

    /**
     * Handler模型对象
     * @var \app\admin\model\handler\Handler
     */
    protected $model = null;
    /**
     * 无需鉴权的方法(需登录)
     * @var array
     */
    protected $noNeedRight = [ 'change', 'searchlist', 'selectpage'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\handler\Handler;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['level'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 切换
     */
    public function change($ids = '')
    {
        //你需要在此做具体的操作逻辑

        $handler = $this->model->find($ids);
        if (!$handler) {
            throw new \Exception('打手不存在');
        }
        $originalStatus = $handler->custom;
        // 更新订单状态
        $handler->custom = $originalStatus == 1 ? 0 : 1;
        $handler->save();

        $this->success("切换成功");
    }

    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            Db::startTrans();
            try {
                $totalAmount = request()->post("amount");
                if($totalAmount <= 0){
                    $this->error('结算金额不正确');
                }
                if (bccomp($row->money, $totalAmount, 2) < 0) {
                    $this->error('打手余额不足，当前余额：¥' . $row->money . '，结算金额：¥' . $totalAmount);
                }
                // 扣除用户余额
                $newBalance = bcsub($row->money, $totalAmount, 2);
                $updateResult = \think\Db::name('handler')
                    ->where('id', $ids)
                    ->update([
                        'money' => $newBalance,
                        'updatetime' => time()
                    ]);

                if ($updateResult === false) {
                    $this->error('修改用户余额失败');
                }

                // 获取管理员信息和IP地址
                $adminId = session('admin.id') ?: 0;
                $adminName = session('admin.nickname') ?: '系统';
                $ip = request()->ip();

                // 记录用户资金流水
                $moneyLogData = [
                    'handler_id' => $ids,
                    'money' => -$totalAmount,
                    'before' => $row->money,
                    'after' => $newBalance,
                    'memo' => sprintf(
                        '管理员操作：%s(%s) %s了金额 %s，从 %s 变更为 %s | IP：%s',
                        $adminName,
                        $adminId,
                        '结算',
                        abs($totalAmount),
                        $row->money,
                        $newBalance,
                        $ip
                    ),
                    'createtime' => time()
                ];

                $moneyLogResult = \think\Db::name('handler_money_log')->insert($moneyLogData);
                if (!$moneyLogResult) {
                    $this->error('记录资金流水失败');
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success("结算请求成功", null, ['amount'=>$totalAmount,'newBalance' => $newBalance]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }


}
